import { Directive } from 'vue'
import { throttle } from 'lodash-es'

const scrollWeakMap = new WeakMap<HTMLElement, () => void>()

export const vMyScrollLoad: Directive<HTMLElement> = {
  mounted(el, { value }) {
    // 保存 store
    const store = value

    // 发生滚动事件的元素 获取其可视高度
    const tableBodyWrapper = el.querySelector('.el-scrollbar__wrap--hidden-default') as HTMLElement | null
    // 滚动高度
    const scrollView = el.querySelector('.el-scrollbar__view') as HTMLElement | null
    // 实际上存储了所有内容的容器高度
    const tableBody = el.querySelector('.el-table__body') as HTMLElement | null

    if (!tableBodyWrapper || !scrollView || !tableBody) {
      console.warn('未找到表格相关元素')
      return
    }

    // 滚动事件处理函数
    const handleScroll = () => {
      // 实时计算各项高度
      const tableHeight = tableBodyWrapper.offsetHeight
      const tableTotalHeight = scrollView.offsetHeight
      const tableScrollHeight = tableBody.scrollHeight

      // 计算滚动距离（判断是否触底）
      const rollingHeight = tableScrollHeight - tableHeight - tableTotalHeight
      const isNearBottom = rollingHeight < 10

      if (isNearBottom) {
        console.log('触底了')
        // 可以通过binding.value传递触底事件给组件
        // binding.value?.()
      }
    }

    // 节流处理滚动事件
    const throttledFn = throttle(handleScroll, 500)
    // 绑定滚动事件（在滚动时实时触发）
    tableBodyWrapper.addEventListener('scroll', throttledFn)

    // 存储滚动事件处理函数
    scrollWeakMap.set(el, () => {
      tableBodyWrapper.removeEventListener('scroll', handleScroll)
    })
  },
  unmounted(el) {
    // 移除滚动事件
    const removeScroll = scrollWeakMap.get(el)
    if (removeScroll) {
      removeScroll()
      // 清空引用
      scrollWeakMap.delete(el)
    }
  }
}
